package com.itfreer.gather.setting;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.itfreer.arcgis.layer.LayerLoader;
import com.itfreer.file.path.FileUpload;
import com.itfreer.file.remote.FileProgressListener;
import com.itfreer.file.remote.download.FileDownloader;
import com.itfreer.gather.R;
import com.itfreer.gis.config.BaseMapService;
import com.itfreer.gis.config.entity.BaseMapEntity;
import com.itfreer.ui.activity.BaseActivity;
import com.itfreer.ui.base.TextView;

import java.io.File;
import java.util.List;

/**
 * 移动端基础底图配置
 */
public class BaseMapActivity extends BaseActivity {

    private ProgressDialog dataSynDialog;
    private LinearLayout setting_base_map_content;
    private LoadBaseMapHandler loadBaseMapHandler;
    private DataSynHandler dataSynHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting_base_map_activity);

        setting_base_map_content =(LinearLayout)findViewById(R.id.setting_base_map_content);
        loadBaseMapHandler = new LoadBaseMapHandler();
        dataSynHandler = new DataSynHandler();
        dataSynDialog = new ProgressDialog(this);

        loadBaseMap();

        // 打开时同步一次
        new Thread(new Runnable() {
            @Override
            public void run() {
                if(BaseMapService.instance.syn()){
                    // 重新加载
                    Message msg = new Message();
                    Bundle b = new Bundle();
                    msg.setData(b);
                    loadBaseMapHandler.sendMessage(msg);
                }
            }
        }).start();
    }

    public void back(View v) {
        finish();
    }

    private class LoadBaseMapHandler extends Handler {
        public LoadBaseMapHandler() {
        }

        // 子类必须重写此方法，接受数据
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            loadBaseMap();
        }
    }

    /**
     * 加载信息
     */
    private void loadBaseMap(){
        setting_base_map_content.removeAllViews();
        List<BaseMapEntity> msgs = BaseMapService.instance.getEntitys();
        if(msgs==null || msgs.size()<=0){
            return;
        }

        for(BaseMapEntity msg : msgs){
            loadBaseMap(msg);
        }
    }

    private void loadBaseMap(BaseMapEntity msg) {
        final float scale = this. getResources().getDisplayMetrics().density;
        int dp15 = (int) (15 * scale + 0.5f);
        int dp20 = (int) (20 * scale + 0.5f);
        int dp25 = (int) (25 * scale + 0.5f);

        RelativeLayout item = new RelativeLayout(BaseMapActivity.this);
        LinearLayout.LayoutParams itemParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        itemParams.setMargins(dp15, dp15, dp15, dp15);
        item.setLayoutParams(itemParams);

        TextView title = new TextView(BaseMapActivity.this);
        RelativeLayout.LayoutParams titleParams = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, dp20);
        titleParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        title.setLayoutParams(titleParams);
        title.setGravity(Gravity.CENTER);
        title.setTextColor(Color.parseColor("#232323"));
        title.setTextSize(16);
        title.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
        if(isDownload(msg)){
            title.setText(msg.getName()+"(已下载)");
        }else{
            title.setText(msg.getName());
        }
        item.addView(title);

        TextView sizeView = new TextView(BaseMapActivity.this);
        RelativeLayout.LayoutParams sizeParams = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, dp20);
        sizeParams.setMargins(0,0, dp25,0);
        sizeParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        sizeView.setLayoutParams(sizeParams);
        sizeView.setGravity(Gravity.CENTER);
        sizeView.setTextColor(Color.parseColor("#bbbbbb"));
        sizeView.setTextSize(16);
        sizeView.setText(Double.toString(msg.getSize()) + "M");
        item.addView(sizeView);

        TextView downView = new TextView(BaseMapActivity.this);
        RelativeLayout.LayoutParams downParams = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, dp20);
        downParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        downView.setLayoutParams(downParams);
        downView.setGravity(Gravity.CENTER);
        downView.setTextColor(Color.parseColor("#69a5fc"));
        downView.setTextSize(16);
        downView.setText(R.string.download);
        downView.setFontName("gather.ttf");
        item.addView(downView);

        // 点击时，开始下载数据
        item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                download(msg);
            }
        });

        setting_base_map_content.addView(item);
    }

    private boolean isDownload(BaseMapEntity item){
        String path = item.getPath();
        String[] paths = path.split(":");
        String buckt = paths[0];
        String key = paths[1];

        // 如果在，说明没有修改过，无需重新下载
        String file = FileUpload.instance.getFile(buckt, key);
        File zipFile = new File(file);
        return zipFile.exists();
    }

    private void download(BaseMapEntity item){
        String path = item.getPath();
        String[] paths = path.split(":");
        String buckt = paths[0];
        String key = paths[1];

        // 如果在，说明没有修改过，无需重新下载
        String file = FileUpload.instance.getFile(buckt, key);
        File zipFile = new File(file);
        if(!zipFile.exists()){
            // 单线程，同步下载文件
            FileDownloader downloader = new FileDownloader(buckt, key);
            showDataSynDialog();
            downloader.download(new FileProgressListener(){
                @Override
                public void onSize(Long count, Long size) {
                    Message msg = new Message();
                    Bundle b = new Bundle();
                    b.putLong("progress", size);
                    b.putLong("count", count);
                    msg.setData(b);
                    dataSynHandler.sendMessage(msg);
                    if(count==size){
                        LayerLoader.instance.setMapIsLoad(false);
                    }
                }
                @Override
                public void onFail(String info) {

                }
            });
        }
    }

    /**
     * 启动数据同步进度对话框
     */
    private void showDataSynDialog(){
        // 设置对话框参数
        dataSynDialog.setTitle("影像下载");
        dataSynDialog.setMessage("数据下载中...");
        dataSynDialog.setCancelable(false);
        // 设置进度条参数
        dataSynDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dataSynDialog.setMax(9);
        dataSynDialog.setProgress(0);
        dataSynDialog.setIndeterminate(false); // 填false表示是明确显示进度的 填true表示不是明确显示进度的
        dataSynDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        dataSynDialog.show();
    }

    private class DataSynHandler extends Handler {
        public DataSynHandler() {
        }

        // 子类必须重写此方法，接受数据
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // 此处可以更新UI
            Bundle b = msg.getData();
            Long size = b.getLong("progress");
            Long count = b.getLong("count");

            int isize = Integer.parseInt(size.toString());
            int icount = Integer.parseInt(count.toString());

            dataSynDialog.setProgress(isize);
            dataSynDialog.setMax(icount);
        }
    }
}


